package cn.seamus.marksman.processor.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.util.Assert;

import cn.seamus.marksman.common.Constants;
import cn.seamus.marksman.common.MarksmanException;
import cn.seamus.marksman.common.PageNavigator;

/**
 * 
 * 
 * <p>
 * Login by page
 * </p>
 * 
 * @author zhengss
 * @version 0.0.1
 * @see
 */
public class LoginPageProcessor extends AbstractProcessor {
    private static Log logger = LogFactory.getLog(LoginPageProcessor.class);

    private String loginPageUrl;

    private int loginTimeout;

    private String loginUsername;

    private String loginPassword;

    @Override
    protected Map<String, Object> prepareNext(Map<String, Object> params) throws MarksmanException {
        return params;
    }

    /*
     * (non-Javadoc)
     * 
     * @see cn.seamus.marksman.processor.Processor#execute()
     */
    @Override
    public ProcessResult read(Map<String, Object> reqMap) throws MarksmanException {
        logger.info("【登录页面】begin.");
        Assert.isTrue(StringUtils.isNotBlank(loginPageUrl));
        Assert.isTrue(StringUtils.isNotBlank(loginUsername));
        Assert.isTrue(StringUtils.isNotBlank(loginPassword));

        // open
        URL loginPageURL = null;

        try {
            loginPageURL = new URL(loginPageUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create loginPageURL: loginPageUrl=" + loginPageUrl, e);
        }

        logger.info("【登录页面】URL= " + loginPageURL.toString());
        logger.info("【登录页面】Connecting...");
        CloseableHttpResponse response = executeGet(loginPageURL, null);

        ProcessResult result = new ProcessResult();
        Map<String, Object> resMap = new HashMap<String, Object>();
        result.setParams(resMap);
        try {

            String body = EntityUtils.toString(response.getEntity());

            Document doc = Jsoup.parse(body);

            Element inputForm = doc.getElementById("customer_login");
            String actionUrl = inputForm.attr("action");
            String actionMethod = inputForm.attr("method");

            resMap.put(Constants.PARAM_KEY_LOGIN_ACTION_URL, actionUrl);
            resMap.put(Constants.PARAM_KEY_LOGIN_ACTION_METHOD, actionMethod);

            result.setNavigator(PageNavigator.DO_LOGIN);

            logger.info("【登录页面】actionUrl=" + actionUrl + ", method=" + actionMethod);
        } catch (IOException e) {
            throw new MarksmanException("Cannot parse  content", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        logger.info("【登录页面】done.");

        return result;
    }

    /**
     * @return the loginTimeout
     */
    public int getLoginTimeout() {
        return loginTimeout;
    }

    /**
     * @param loginTimeout
     *            the loginTimeout to set
     */
    public void setLoginTimeout(int loginTimeout) {
        this.loginTimeout = loginTimeout;
    }

    /**
     * @return the loginPageUrl
     */
    public String getLoginPageUrl() {
        return loginPageUrl;
    }

    /**
     * @param loginPageUrl
     *            the loginPageUrl to set
     */
    public void setLoginPageUrl(String loginPageUrl) {
        this.loginPageUrl = loginPageUrl;
    }

    /**
     * @return the loginUsername
     */
    public String getLoginUsername() {
        return loginUsername;
    }

    /**
     * @param loginUsername
     *            the loginUsername to set
     */
    public void setLoginUsername(String loginUsername) {
        this.loginUsername = loginUsername;
    }

    /**
     * @return the loginPassword
     */
    public String getLoginPassword() {
        return loginPassword;
    }

    /**
     * @param loginPassword
     *            the loginPassword to set
     */
    public void setLoginPassword(String loginPassword) {
        this.loginPassword = loginPassword;
    }

}
